package org.autumn.algorithm.sort;

public abstract class AbstractSort implements Sort {


    @Override
    public void sort(int[] arr) {
        if (verify(arr)) return;
        doSort(arr);
    }

    public abstract void doSort(int[] arr);

    public void swap(int[] arr, int p1, int p2) {
        int t = arr[p1];
        arr[p1] = arr[p2];
        arr[p2] = t;
    }

    /**
     * 异或交换
     * for example:
     * arr[p1]=4 and arr[p2]=8
     * 0000 0100
     * 0000 1000
     * ---------  ^
     * 0000 1100
     * <p>
     * arr[p1] = 12
     * 0000 1100
     * 0000 1000
     * ---------  ^
     * 0000 0100 4
     * arr[p2] = 4
     * 0000 1100
     * 0000 0100
     * ---------  ^
     * 0000 1000
     * arr[p1] = 8
     */
    public void xorSwap(int[] arr, int p1, int p2) {
        arr[p1] = arr[p1] ^ arr[p2];
        arr[p2] = arr[p1] ^ arr[p2];
        arr[p1] = arr[p1] ^ arr[p2];
    }

    public boolean verify(int[] arr) {
        return arr == null || arr.length < 2;
    }
}
